﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using BaicaiTianqi.Model;
using System.Diagnostics;
using System.IO;
using System.Windows.Media.Imaging;
using BaicaiTianqi.View;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;

namespace BaicaiTianqi
{
    public partial class MainPage : PhoneApplicationPage
    {
        PopupCotainer pc;
        CityInput ci;
        // 构造函数
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            Weatherinfo infoLocal = AppSettingsHelper.GetValueOrDefault("WeatherInfo", new Weatherinfo());
            if (infoLocal == null || infoLocal.city == null)
            {
                ci = new CityInput();
                ci.button1.Click += new RoutedEventHandler(button1_Click);
                pc = new PopupCotainer(this);
                pc.Show(ci);
            }
            else
            {
                Loadinfo(infoLocal);
                mainProgressBar.Visibility = Visibility.Visible;
                if (!Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("网络连接出错，请检查网络设置。");
                        mainProgressBar.Visibility = Visibility.Collapsed;
                    });
                    return;
                }
                HttpHelper helper = new HttpHelper();
                helper.StartRequest(@"http://m.weather.com.cn/data/"+infoLocal.cityid+".html",
                    result =>
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            if (result != null && !result.Equals(""))
                            {
                                Weatherinfo info = JsonSerializerHelper.Deserialize<Weatherinfo>(result);
                                AppSettingsHelper.AddOrUpdateValue("WeatherInfo", info);
                                Loadinfo(info);
                                backTileImage1.LoadInfo();
                                UpdateTile();
                            }
                        });
                    });
            }
        }

        void button1_Click(object sender, RoutedEventArgs e)
        {
            mainProgressBar.Visibility = Visibility.Visible;
            HttpHelper helper = new HttpHelper();
            String city = CityList.getCityId(ci.textBox1.Text);
            if (city.Equals(""))
            {
                MessageBox.Show("不支持的城市！(请不要在城市名称后加‘市’‘县’等行政等级)");
                return;
            }
            if (pc != null)
            {
                pc.Close();
                pc = null;
            }
            if (!Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络连接出错，请检查网络设置。");
                    mainProgressBar.Visibility = Visibility.Collapsed;
                });
                return;
            }
            helper.StartRequest(@"http://m.weather.com.cn/data/" + CityList.getCityId(ci.textBox1.Text) + ".html",
                result =>
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        if (result != null && !result.Equals(""))
                        {
                            Weatherinfo info = JsonSerializerHelper.Deserialize<Weatherinfo>(result);
                            AppSettingsHelper.AddOrUpdateValue("WeatherInfo", info);
                            Loadinfo(info);
                            backTileImage1.LoadInfo();
                            UpdateTile();
                        }
                    });
                });
        }

        private void Loadinfo(Weatherinfo info)
        {
            today.Text = info.city;
            Condition.Text = info.weather1;
            Temp.Text = info.temp1;
            //Humidity.Text = "紫外线:"+info.index_uv;
            //WindCondition.Text = info.wind1;
            Date.Text = info.date_y;

            Imagetoday.Source = new BitmapImage(new Uri(IconList.getIconUri(Int32.Parse(info.img1)),
                UriKind.RelativeOrAbsolute));

            TopLine01.Y1 = 230 - 3 * (getTemp(info.temp1)[1]);
            LowLine01.Y1 = 230 - 3 * (getTemp(info.temp1)[0]);

            TextBlock1.Text = String.Format(info.weather2 + "\n" + info.temp2);
            image1.Source = new BitmapImage(new Uri(IconList.getIconUri(Int32.Parse(info.img2)),
                UriKind.RelativeOrAbsolute));
            TopLine01.Y2 = 230 - 3 * (getTemp(info.temp2)[1]);
            TopLine12.Y1 = 230 - 3 * (getTemp(info.temp2)[1]);
            LowLine01.Y2 = 230 - 3 * (getTemp(info.temp2)[0]);
            LowLine12.Y1 = 230 - 3 * (getTemp(info.temp2)[0]);

            TextBlock2.Text = String.Format(info.weather3 + "\n" + info.temp3);
            image2.Source = new BitmapImage(new Uri(IconList.getIconUri(Int32.Parse(info.img3)),
                UriKind.RelativeOrAbsolute));
            TopLine12.Y2 = 230 - 3 * (getTemp(info.temp3)[1]);
            TopLine23.Y1 = 230 - 3 * (getTemp(info.temp3)[1]);
            LowLine12.Y2 = 230 - 3 * (getTemp(info.temp3)[0]);
            LowLine23.Y1 = 230 - 3 * (getTemp(info.temp3)[0]);

            TextBlock3.Text = String.Format(info.weather4 + "\n" + info.temp4);
            image3.Source = new BitmapImage(new Uri(IconList.getIconUri(Int32.Parse(info.img4)),
                UriKind.RelativeOrAbsolute));
            TopLine23.Y2 = 230 - 3 * (getTemp(info.temp4)[1]);
            LowLine23.Y2 = 230 - 3 * (getTemp(info.temp4)[0]);
            tbjianyi.Text = info.index_d;
            mainProgressBar.Visibility = Visibility.Collapsed;
        }

        private int[] getTemp(string s)
        {
            s = s.Replace("℃", "");
            int i = Int32.Parse(s.Split('~')[0]);
            int j = Int32.Parse(s.Split('~')[1]);
            int[] ints = new int[] { i, j };
            return ints;
        }

        private void CitySet_Click(object sender, EventArgs e)
        {
            ci = new CityInput();
            ci.button1.Click += new RoutedEventHandler(button1_Click);
            pc = new PopupCotainer(this);
            pc.Show(ci);
        }

        private void PinStart_Click(object sender, EventArgs e)
        {
            backTileImage1.LoadInfo();
            NewTile();
        }

        private void NewTile()
        {
            ShellTile TileToFind = ShellTile.ActiveTiles.FirstOrDefault
                (x => x.NavigationUri.ToString().Contains("DefaultTitle=Tile"));

            if (TileToFind == null)
            {
                Weatherinfo infoLocal = AppSettingsHelper.GetValueOrDefault("WeatherInfo", new Weatherinfo());
                if (!today.Text.Equals("请设置城市"))
                {
                    StandardTileData NewTileData = new StandardTileData
                    {
                        Title = String.Format(infoLocal.city + " " + infoLocal.temp1),
                        BackBackgroundImage = new Uri(CreateBackBackground()),
                        BackgroundImage = new Uri(IconList.getIconUri(Int32.Parse(infoLocal.img1)), UriKind.RelativeOrAbsolute),
                        BackTitle = "白菜天气"
                    };
                    ShellTile.Create(new Uri("/MainPage.xaml?DefaultTitle=Tile", UriKind.Relative), NewTileData);
                }
            }
        }
        private void UpdateTile()
        {
            ShellTile TileToFind = ShellTile.ActiveTiles.FirstOrDefault
                            (x => x.NavigationUri.ToString().Contains("DefaultTitle=Tile"));
            if (TileToFind != null)
            {
                Weatherinfo infoLocal = AppSettingsHelper.GetValueOrDefault("WeatherInfo", new Weatherinfo());
                StandardTileData NewTileData = new StandardTileData
                {
                    Title = String.Format(infoLocal.city + " " + infoLocal.temp1),
                    BackBackgroundImage = new Uri(CreateBackBackground()),
                    BackgroundImage = new Uri(IconList.getIconUri(Int32.Parse(infoLocal.img1)), UriKind.RelativeOrAbsolute),
                    BackTitle = "白菜天气"
                };

                TileToFind.Update(NewTileData);
            }
        }
        private string CreateBackBackground()
        {
            WriteableBitmap wbmp = new WriteableBitmap(backTileImage1, null);

            string tiledirectory = "Shared/ShellContent/tiles";//note :父目录必须是 Shared/ShellContent
            string fullPath = tiledirectory + @"/" + "BackLiveTile.jpg";
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.DirectoryExists(tiledirectory))
                {
                    store.CreateDirectory(tiledirectory);
                }
                try
                {
                    using (var stream = store.OpenFile(fullPath, System.IO.FileMode.OpenOrCreate))
                    {
                        wbmp.SaveJpeg(stream, 173, 173, 0, 100);
                    }
                }
                catch (Exception)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        today.Text = "今日天气";
                        MessageBox.Show("信息处理异常，请刷新再试。");
                    });
                }

            }
            return "isostore:/" + fullPath;
        }
    }
}